using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Routing;
using EPiAbstractions;
using EPiServer.Core;
using JoelAbrahamsson.FeedImport;
using JoelAbrahamsson.PageTypes;

namespace JoelAbrahamsson.Web.Controllers
{
    public class TwitterFeedController : Controller
    {
        private IDataFactoryFacade _dataFactoryFacade;
        private int defaultItemCount = 3;

        public TwitterFeedController(IDataFactoryFacade dataFactoryFacade)
        {
            _dataFactoryFacade = dataFactoryFacade;
        }

        public ActionResult Index(int? twitterItemsCount)
        {
            if (!twitterItemsCount.HasValue)
                twitterItemsCount = defaultItemCount;
            
            Start startPage = (Start) _dataFactoryFacade.GetPage(PageReference.StartPage);
            if (startPage.TwitterFeedRoot == null)
                return View(new List<SyndicationFeedItem>());

            IEnumerable<SyndicationFeedItem> items = _dataFactoryFacade.GetChildren(startPage.TwitterFeedRoot.PageLink).Cast<SyndicationFeedItem>();
            int totalItems = items.Count();
            int skip = 0;
            if (Request.IsAjaxRequest())
                skip = twitterItemsCount.Value - defaultItemCount;
            items = items.Skip(skip).Take(defaultItemCount);
            return View(items);
        }
    }
}
